
import { Component, ViewChild, ElementRef, ViewChildren, Renderer2, OnInit } from '@angular/core';
import { NavController, IonContent, Events } from '@ionic/angular';
// import { Storage } from '@ionic/storage';
// import { NativeService } from '../../services/native.service';
// import { RestService } from '../../services/rest.services';
// import Bscroll from 'better-scroll';


@Component({
  selector: 'app-a-zlist',
  templateUrl: './a-zlist.page.html',
  styleUrls: ['./a-zlist.page.scss'],
})
export class AZlistPage implements OnInit {
  @ViewChild(IonContent, { static: true }) content: IonContent;
  @ViewChildren('cityGroup', { read: true }) cityGroup: ElementRef;
  @ViewChildren('list', { read: true }) list: ElementRef;
  @ViewChild("containermap", { static: true }) containermap: ElementRef;


  curPos: string = ""; //当前定位
  cities: Array<any> = []; //城市数组
  oriCities: Array<any> = []; //城市数组--接口返回值

  filteredCities: Array<any> = []; //过滤城市数组

  cacheSearchCity: Array<any> = [];//历史搜索

  resetPosition: string = "";

  public scroll;

  //右侧字母排序数组
  rightIndexes = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
  constructor(
    public navCtrl: NavController,
    private el: ElementRef,
    // public navParams: NavParams,
    // public nativeService: NativeService,
    // public storage: Storage,
    public ele: ElementRef,
    public r2: Renderer2,
    // public restService: RestService,
    public events: Events,
  ) {
    // this.curPos = this.navParams.data.curPosition;
    // this.storage.get("city_history").then(cacheCity => {
    //   this.cacheSearchCity = cacheCity;
    // });


  }



  ngOnInit() {
    var data = [{ pinyin: 'beijing', name: '北京市', index: 'B', id: '1' },
    { pinyin: 'beijing', name: '北京市', index: 'B', id: '1' }, { pinyin: 'beijing', name: '北京市', index: 'B', id: '1' }, { pinyin: 'beijing', name: '北京市', index: 'B', id: '1' }, { pinyin: 'beijing', name: '北京市', index: 'B', id: '1' }, { pinyin: 'beijing', name: '北京市', index: 'B', id: '1' },
    { pinyin: 'tianjin', name: '天津市', index: 'T', id: '2' },
    { pinyin: 'shanghai', name: '上海市', index: 'S', id: '2' },
    { pinyin: 'chongqiong', name: '重庆市', index: 'C', id: '3' },

    ]
    // this.storage.get("citydata")
    //   .then(data => {
    //     if (data) {
    this.cities = this.getGroupCities(data);
    this.oriCities = data;
    // } else {
    // this.restService.locationCity()
    //   .subscribe((citisArr: any) => {
    //     console.log(citisArr)
    //     this.oriCities = citisArr.body.cities;
    //     this.cities = this.getGroupCities(this.oriCities);
    //     // this.storage.set("citydata", this.oriCities);
    //   })
    // }
    // })
  }

  ionViewDidEnter() {
    // this.scroll = new Bscroll(this.content..children[1]);
  }


  /*
  * 重新定位
  * @memberof LocationPage
  */
  getPosition() {
    this.resetPosition = "定位中...";
    this.getResetPos().then((data: string) => {
      this.resetPosition = data;
    }, (err) => {
      this.resetPosition = "定位失败";
    })
  }

  getResetPos() {
    return new Promise((resolve, reject) => {
      (<any>window).GaoDe.getCurrentPosition((successData) => {
        resolve(successData.city)
      }, (faileData) => {
        reject("定位失败");
      });
    })
  }

  IndexTouchStart(ev) {
    this.alphabetMove(ev, true);
  }


  /**
   *
   * 滚动效果
   * @param {*} e
   * @param {*} move
   * @returns
   * @memberof LocationPage
   */
  alphabetMove(e, move) {
    let currentItem;
    currentItem = e.target;
    if (!currentItem || currentItem.className.indexOf('letter') < 0) return;
    console.log(currentItem.className.indexOf('letter'));
    if (move) {
      let index = this.rightIndexes.join('').indexOf(currentItem.innerText);
      console.log(index);
      var dassss = this.el.nativeElement.querySelectorAll(".index_title");
      let div = dassss[index];
      let scrollHeight = div.offsetTop;
      let scrollx = div.offsetLeft;
      this.content.scrollToPoint(scrollx, scrollHeight + 15, 300);
    }
  }






  /**
   * 城市分组排序
   */
  getGroupCities(cities) {
    var group = [];
    this.rightIndexes.forEach(c => {
      let cCities = cities.filter(cityItem => cityItem.index === c);
      console.log(cCities.length);
      var datas = this.getRowListByGridList(cCities, 3);
      group.push({
        index: c,
        cities: datas
      })
    });
    return group;
  }
  getRowListByGridList(gridList, size): any[] {
    var rowList = []
    for (var i = 0; i < gridList.length; i += size) {
      rowList.push(gridList.slice(i, i + size));
    }

    return rowList;
  }


  /**
   * 点击选择搜索的城市
   * @param city 选择的城市
   */
  citySelect(city) {
    // this.storage.get("city_history").then((cities: any) => {
    //   if (cities == null) cities = [];
    //   cities.forEach((element, index) => {
    //     if (city.name == element.name) {
    //       cities.splice(index, 1);
    //     }
    //   });
    //   if (cities.length >= 3) {
    //     cities.pop();
    //     cities.unshift(city);
    //     // this.storage.set("city_history", cities);
    //     this.cacheSearchCity = cities;
    //   } else {
    //     cities.unshift(city);
    //     // this.storage.set("city_history", cities);
    //     this.cacheSearchCity = cities;
    //   }
    //   this.navCtrl.pop();
    //   this.events.publish("select_postion", city);
    // })

  }


  /**
   *城市搜索
   *
   * @memberof LocationPage
   */
  getItems(ev) {
    var newVal = ev.target.value;
    if (newVal) {
      this.filteredCities = this.filterCities(newVal);
    }
    else {
      this.filteredCities = [];
    }
    this.content.scrollToTop(500);
  }


  /**
   *过滤符合条件的城市
   *
   * @param {*} val
   * @memberof LocationPage
   */
  filterCities(val) {
    var filterCities = [];
    this.oriCities.filter(item => {
      if (item.name.indexOf(val) > -1) {
        filterCities.push(item);
      }
    })
    return filterCities;
  }

  /**
   * 选择当前定位，返回首页
   */
  comfirmCurPostion() {
    this.navCtrl.pop();
  }

}